import java.nio.CharBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author tigger
 * 
 */
public class LineReader {

	private CharBuffer cbuf;
	private static final CharSequence NOLINE = null;
	private static final String SEPARATOR = "\r\n";

	public LineReader(CharBuffer cbuf) {
		this.cbuf = cbuf;
	}

	public CharSequence readLine() {
		CharSequence result;

		CharBuffer workingBuffer = cbuf.asReadOnlyBuffer();
		workingBuffer.flip();
		int cutposition = getCutPosition(workingBuffer);

		if (cutposition == -1) {
			result = NOLINE;
		} else {
			result = getFirstLine(workingBuffer, cutposition);
			trimfirstline(cbuf, cutposition);
		}
		return result;
	}

	public void trimfirstline(CharBuffer buf, int cutposition) {
		// TODO Auto-generated method stub
		//buf.position(0);
		buf.limit(buf.position());
		buf.position(cutposition);
		buf.compact();

	}

	private int getCutPosition(CharBuffer workingBuffer) {
		// TODO Auto-generated method stub
		Pattern p = Pattern.compile(".*?" + SEPARATOR);
		Matcher m = p.matcher(workingBuffer);

		if (m.find()) {
			return m.end();
		} else {
			return -1;
		}

	}

	private CharSequence getFirstLine(CharBuffer cbuf, int cutposition) {
		return cbuf.subSequence(0, cutposition - SEPARATOR.length());
	}

	private boolean isEmpty(CharBuffer cbuf) {
		return cbuf.remaining() == 0;
	}



}
